package com.zmn.oms.business.impl.work.epidemiccontrol;

import com.zmn.aws.common.model.community.CommunityLibraryDRO;
import com.zmn.aws.dubbo.interfaces.community.CommunityListRemoteService;
import com.zmn.base.common.data.common.dro.area.AreaControlDRO;
import com.zmn.base.common.data.common.enums.ControlLevelEnum;
import com.zmn.base.common.data.dubbo.interfaces.area.AreaControlListRemoteService;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.consts.GlobalConsts;
import com.zmn.oms.business.interfaces.work.epidemiccontrol.OrderWorkEpidemicControlBService;
import com.zmn.oms.common.constant.OrderLogConsts;
import com.zmn.oms.common.dto.QueueOrderNodeNotifyDTO;
import com.zmn.oms.model.entity.detail.OrderDetail;
import com.zmn.oms.model.entity.work.OrderWorkEpidemicControl;
import com.zmn.oms.services.interfaces.detail.OrderDetailService;
import com.zmn.oms.services.interfaces.work.epidemiccontrol.OrderWorkEpidemicControlService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 类描述 工单疫情管控
 *
 * @author fubiao
 * @since 2022/08/16
 */
@Service
@Slf4j
public class OrderWorkEpidemicControlBServiceImpl implements OrderWorkEpidemicControlBService {

    @Autowired
    private OrderWorkEpidemicControlService workEpidemicControlService;
    @Resource
    private OrderDetailService orderDetailService;

    @DubboReference(version = com.zmn.base.plat.engine.common.constant.DubboConsts.INTERFACE_VERSION, check = false)
    private AreaControlListRemoteService areaControlListRemoteService;
    @DubboReference(version = com.zmn.aws.dubbo.utils.DubboConstants.INTERFACE_VERSION, check = false)
    private CommunityListRemoteService communityListRemoteService;

    @Override
    public void save(QueueOrderNodeNotifyDTO dto, Integer nodeType) {
        // 前置校验
        if (Objects.isNull(dto.getOrderId()) || Objects.isNull(dto.getWorkId()) || Objects.isNull(nodeType)) {
            log.info("疫情管控缺乏必要数据 orderId=[{}]", dto.getOrderId());
            return;
        }

        OrderDetail orderDetail = orderDetailService.findOrderDetailByKeySrcMaster(dto.getOrderId());
        Integer epidemicControlLevel = this.getEpidemicControlLevel(orderDetail.getCountyId(), dto.getLongitude(),
                dto.getLatitude());

        OrderWorkEpidemicControl workEpidemicControl = new OrderWorkEpidemicControl();
        workEpidemicControl.setOrderId(dto.getOrderId());
        workEpidemicControl.setWorkId(dto.getWorkId());
        workEpidemicControl.setCreater(dto.getOperator());
        workEpidemicControl.setCreateTime(DateUtil.getNow());
        workEpidemicControl.setNodeType(nodeType);

        if (Objects.equals(OrderLogConsts.ORDER_LOG_TYPE_INPUT, nodeType)) {
            // 无疫情 不处理
            if (Objects.equals(GlobalConsts.NONE, epidemicControlLevel)) {
                return;
            }
            // 有疫情新增
            workEpidemicControl.setControlLevel(epidemicControlLevel);
            workEpidemicControlService.insert(workEpidemicControl);
            return;
        }

        OrderWorkEpidemicControl orderWorkEpidemicControl = workEpidemicControlService.findByWorkIdAndNodeType(dto.getOrderId(),
                dto.getWorkId(), nodeType);

        if (Objects.isNull(orderWorkEpidemicControl)) {
            // 无疫情 不处理
            if (Objects.equals(GlobalConsts.NONE, epidemicControlLevel)) {
                return;
            }
            // 有疫情新增
            workEpidemicControl.setControlLevel(epidemicControlLevel);
            workEpidemicControlService.insert(workEpidemicControl);
            return;
        }

        // 无疫情删除
        if (Objects.equals(GlobalConsts.NONE, epidemicControlLevel)) {
            workEpidemicControlService.deleteByWorkIdAndNodeType(dto.getOrderId(), dto.getWorkId(), nodeType);
            return;
        }

        // 疫情信息一致 不处理
        if (Objects.equals(orderWorkEpidemicControl.getControlLevel(), epidemicControlLevel)) {
            return;
        }

        // 修改疫情信息
        workEpidemicControl.setControlLevel(epidemicControlLevel);
        workEpidemicControl.setUpdater(dto.getOperator());
        workEpidemicControlService.updateByWorkIdAndNodeType(workEpidemicControl);
    }

    @Override
    public Integer getEpidemicControlLevel(Integer countyId, Double longitude, Double latitude) {
        if (log.isDebugEnabled()) {
            log.debug("#getEpidemicControlLevel入参 countyId={} longitude={}, latitude={}", countyId, longitude, latitude);
        }

        if (Objects.isNull(countyId) || Objects.isNull(longitude) || Objects.isNull(latitude)) {
            log.info("获取疫情级别必要参数为空 countyId={} longitude={}, latitude={}", countyId, longitude, latitude);
            return GlobalConsts.NONE;
        }

        ResponseDTO<List<CommunityLibraryDRO>> communityInfoResponseDTO = communityListRemoteService
                .listCommunityInfoByLngAndLat(longitude.toString(), latitude.toString());
        if (Objects.isNull(communityInfoResponseDTO.getData())) {
            return GlobalConsts.NONE;
        }

        if (log.isDebugEnabled()) {
            log.debug("#getEpidemicControlLevel获取小区信息出参 resp={}", communityInfoResponseDTO.getData());
        }

        List<Integer> communityIds = communityInfoResponseDTO.getData().stream().
                map((CommunityLibraryDRO::getCommunityId)).collect(Collectors.toList());
        ResponseDTO<List<AreaControlDRO>> areaControlResponseDTO = areaControlListRemoteService
                .listByCommunityIdsAndCountyId(countyId, communityIds);
        if (Objects.isNull(areaControlResponseDTO.getData())) {
            return GlobalConsts.NONE;
        }

        if (log.isDebugEnabled()) {
            log.debug("#communityInfoResponseDTO获取疫情管控信息出参 resp={}", areaControlResponseDTO.getData());
        }

        return getEpidemicControlLevelByAreaControlList(areaControlResponseDTO.getData());
    }

    private Integer getEpidemicControlLevelByAreaControlList(List<AreaControlDRO> droList) {
        if (CollectionUtil.isNullOrEmpty(droList)) {
            return GlobalConsts.NONE;
        }
        // 封控
        if (droList.stream().anyMatch(dro -> Objects.equals(ControlLevelEnum.CONTROLLED_ZONES.getCode(), dro.getControlLevel()))) {
            return ControlLevelEnum.CONTROLLED_ZONES.getCode();
        }
        // 管控
        if (droList.stream().anyMatch(dro -> Objects.equals(ControlLevelEnum.LOCKDOWN_ZONES.getCode(), dro.getControlLevel()))) {
            return ControlLevelEnum.LOCKDOWN_ZONES.getCode();
        }
        // 防控
        return ControlLevelEnum.PRECAUTIONARY_ZONES.getCode();
    }
}
